<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统 - 功能测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 40px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }

        .section-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            font-weight: bold;
            color: #495057;
        }

        .section-content {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #495057;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin: 5px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(81, 207, 102, 0.4);
        }

        .response-area {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            margin-top: 15px;
            max-height: 300px;
            overflow-y: auto;
        }

        .response-area pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .user-list {
            margin-top: 20px;
        }

        .user-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .user-info {
            flex: 1;
        }

        .user-actions {
            display: flex;
            gap: 5px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #667eea;
        }

        .loading.show {
            display: block;
        }

        .error {
            color: #dc3545;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }

        .success {
            color: #155724;
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }

        .api-info {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .api-info h3 {
            color: #1976d2;
            margin-bottom: 10px;
        }

        .api-endpoint {
            font-family: 'Courier New', monospace;
            background: #f5f5f5;
            padding: 5px 10px;
            border-radius: 3px;
            margin: 5px 0;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 用户管理系统</h1>
            <p>基于 Node.js + Express + MySQL 的用户CRUD接口测试</p>
        </div>

        <div class="content">
            <!-- API 信息 -->
            <div class="api-info">
                <h3>📚 API 接口文档</h3>
                <p><strong>基础URL:</strong> <span class="api-endpoint">http://localhost:2230/api/users</span></p>
                <div style="margin-top: 10px;">
                    <div><strong>POST</strong> <span class="api-endpoint">/</span> - 创建用户</div>
                    <div><strong>GET</strong> <span class="api-endpoint">/</span> - 获取用户列表（支持分页和筛选）</div>
                    <div><strong>GET</strong> <span class="api-endpoint">/:id</span> - 获取单个用户</div>
                    <div><strong>PUT</strong> <span class="api-endpoint">/:id</span> - 更新用户</div>
                    <div><strong>DELETE</strong> <span class="api-endpoint">/:id</span> - 删除用户</div>
                    <div><strong>POST</strong> <span class="api-endpoint">/batch-delete</span> - 批量删除用户</div>
                    <div><strong>POST</strong> <span class="api-endpoint">/login</span> - 用户登录</div>
                </div>
            </div>

            <!-- 创建用户 -->
            <div class="section">
                <div class="section-header">➕ 创建用户</div>
                <div class="section-content">
                    <div class="grid">
                        <div class="form-group">
                            <label for="createUsername">用户名 *</label>
                            <input type="text" id="createUsername" placeholder="请输入用户名（字母数字，3-50字符）">
                        </div>
                        <div class="form-group">
                            <label for="createPassword">密码 *</label>
                            <input type="password" id="createPassword" placeholder="请输入密码（至少6字符）">
                        </div>
                        <div class="form-group">
                            <label for="createRealName">真实姓名</label>
                            <input type="text" id="createRealName" placeholder="请输入真实姓名">
                        </div>
                        <div class="form-group">
                            <label for="createPhone">手机号码</label>
                            <input type="text" id="createPhone" placeholder="请输入手机号码">
                        </div>
                        <div class="form-group">
                            <label for="createRole">角色</label>
                            <select id="createRole">
                                <option value="user">普通用户</option>
                                <option value="manager">管理员</option>
                                <option value="admin">超级管理员</option>
                            </select>
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="createUser()">创建用户</button>
                    <div class="response-area" id="createResponse"></div>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="section">
                <div class="section-header">📋 用户列表</div>
                <div class="section-content">
                    <div class="grid">
                        <div class="form-group">
                            <label for="listPage">页码</label>
                            <input type="number" id="listPage" value="1" min="1">
                        </div>
                        <div class="form-group">
                            <label for="listLimit">每页数量</label>
                            <input type="number" id="listLimit" value="10" min="1" max="100">
                        </div>
                        <div class="form-group">
                            <label for="listUsername">用户名筛选</label>
                            <input type="text" id="listUsername" placeholder="输入用户名关键字">
                        </div>
                        <div class="form-group">
                            <label for="listRole">角色筛选</label>
                            <select id="listRole">
                                <option value="">全部角色</option>
                                <option value="user">普通用户</option>
                                <option value="manager">管理员</option>
                                <option value="admin">超级管理员</option>
                            </select>
                        </div>
                    </div>
                    <button class="btn btn-primary" onclick="getUserList()">获取用户列表</button>
                    <div class="loading" id="listLoading">📡 正在加载用户列表...</div>
                    <div class="user-list" id="userList"></div>
                    <div class="response-area" id="listResponse"></div>
                </div>
            </div>

            <!-- 获取单个用户 -->
            <div class="section">
                <div class="section-header">👤 获取单个用户</div>
                <div class="section-content">
                    <div class="form-group">
                        <label for="getUserId">用户ID</label>
                        <input type="number" id="getUserId" placeholder="请输入用户ID">
                    </div>
                    <button class="btn btn-primary" onclick="getUserById()">获取用户信息</button>
                    <div class="response-area" id="getUserResponse"></div>
                </div>
            </div>

            <!-- 更新用户 -->
            <div class="section">
                <div class="section-header">✏️ 更新用户</div>
                <div class="section-content">
                    <div class="grid">
                        <div class="form-group">
                            <label for="updateUserId">用户ID *</label>
                            <input type="number" id="updateUserId" placeholder="请输入要更新的用户ID">
                        </div>
                        <div class="form-group">
                            <label for="updateUsername">用户名</label>
                            <input type="text" id="updateUsername" placeholder="新用户名（可选）">
                        </div>
                        <div class="form-group">
                            <label for="updatePassword">密码</label>
                            <input type="password" id="updatePassword" placeholder="新密码（可选）">
                        </div>
                        <div class="form-group">
                            <label for="updateRealName">真实姓名</label>
                            <input type="text" id="updateRealName" placeholder="新真实姓名（可选）">
                        </div>
                        <div class="form-group">
                            <label for="updatePhone">手机号码</label>
                            <input type="text" id="updatePhone" placeholder="新手机号码（可选）">
                        </div>
                        <div class="form-group">
                            <label for="updateRole">角色</label>
                            <select id="updateRole">
                                <option value="">不修改</option>
                                <option value="user">普通用户</option>
                                <option value="manager">管理员</option>
                                <option value="admin">超级管理员</option>
                            </select>
                        </div>
                    </div>
                    <button class="btn btn-success" onclick="updateUser()">更新用户</button>
                    <div class="response-area" id="updateResponse"></div>
                </div>
            </div>

            <!-- 删除用户 -->
            <div class="section">
                <div class="section-header">🗑️ 删除用户</div>
                <div class="section-content">
                    <div class="grid">
                        <div class="form-group">
                            <label for="deleteUserId">单个删除 - 用户ID</label>
                            <input type="number" id="deleteUserId" placeholder="请输入要删除的用户ID">
                        </div>
                        <div class="form-group">
                            <label for="batchDeleteIds">批量删除 - 用户ID列表</label>
                            <input type="text" id="batchDeleteIds" placeholder="请输入用户ID，用逗号分隔（如：1,2,3）">
                        </div>
                    </div>
                    <button class="btn btn-danger" onclick="deleteUser()">删除单个用户</button>
                    <button class="btn btn-danger" onclick="batchDeleteUsers()">批量删除用户</button>
                    <div class="response-area" id="deleteResponse"></div>
                </div>
            </div>

            <!-- 用户登录 -->
            <div class="section">
                <div class="section-header">🔐 用户登录</div>
                <div class="section-content">
                    <div class="grid">
                        <div class="form-group">
                            <label for="loginUsername">用户名</label>
                            <input type="text" id="loginUsername" placeholder="请输入用户名">
                        </div>
                        <div class="form-group">
                            <label for="loginPassword">密码</label>
                            <input type="password" id="loginPassword" placeholder="请输入密码">
                        </div>
                    </div>
                    <button class="btn btn-success" onclick="loginUser()">登录</button>
                    <div class="response-area" id="loginResponse"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/users';

        // 通用请求函数
        async function makeRequest(url, method = 'GET', data = null) {
            const options = {
                method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                options.body = JSON.stringify(data);
            }

            try {
                const response = await fetch(url, options);
                const result = await response.json();
                return result;
            } catch (error) {
                return {
                    success: false,
                    message: '网络请求失败',
                    error: error.message
                };
            }
        }

        // 显示响应结果
        function displayResponse(elementId, data) {
            const element = document.getElementById(elementId);
            element.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
            
            // 根据结果添加样式
            if (data.success) {
                element.style.borderLeft = '4px solid #28a745';
            } else {
                element.style.borderLeft = '4px solid #dc3545';
            }
        }

        // 创建用户
        async function createUser() {
            const userData = {
                username: document.getElementById('createUsername').value,
                password: document.getElementById('createPassword').value,
                real_name: document.getElementById('createRealName').value,
                phone: document.getElementById('createPhone').value,
                role: document.getElementById('createRole').value
            };

            // 移除空值
            Object.keys(userData).forEach(key => {
                if (!userData[key]) delete userData[key];
            });

            const result = await makeRequest(API_BASE, 'POST', userData);
            displayResponse('createResponse', result);

            if (result.success) {
                // 清空表单
                document.getElementById('createUsername').value = '';
                document.getElementById('createPassword').value = '';
                document.getElementById('createRealName').value = '';
                document.getElementById('createPhone').value = '';
                document.getElementById('createRole').value = 'user';
            }
        }

        // 获取用户列表
        async function getUserList() {
            const loading = document.getElementById('listLoading');
            loading.classList.add('show');

            const params = new URLSearchParams();
            const page = document.getElementById('listPage').value;
            const limit = document.getElementById('listLimit').value;
            const username = document.getElementById('listUsername').value;
            const role = document.getElementById('listRole').value;

            if (page) params.append('page', page);
            if (limit) params.append('limit', limit);
            if (username) params.append('username', username);
            if (role) params.append('role', role);

            const url = `${API_BASE}/getlist?${params.toString()}`;
            const result = await makeRequest(url);
            
            loading.classList.remove('show');
            displayResponse('listResponse', result);

            // 显示用户列表
            displayUserList(result);
        }

        // 显示用户列表
        function displayUserList(result) {
            const userListElement = document.getElementById('userList');
            
            if (result.success && result.data) {
                let html = `<h4>用户列表 (第${result.pagination.current}页，共${result.pagination.total}条记录)</h4>`;
                
                result.data.forEach(user => {
                    html += `
                        <div class="user-item">
                            <div class="user-info">
                                <strong>ID: ${user.id}</strong> - ${user.username} 
                                ${user.real_name ? `(${user.real_name})` : ''} 
                                - 角色: ${user.role}
                                ${user.phone ? ` - 手机: ${user.phone}` : ''}
                                <br><small>最后登录: ${user.last_login_at || '未登录'}</small>
                            </div>
                            <div class="user-actions">
                                <button class="btn btn-success" onclick="fillUpdateForm(${user.id}, '${user.username}', '${user.real_name || ''}', '${user.phone || ''}', '${user.role}')">编辑</button>
                                <button class="btn btn-danger" onclick="quickDelete(${user.id})">删除</button>
                            </div>
                        </div>
                    `;
                });
                
                userListElement.innerHTML = html;
            } else {
                userListElement.innerHTML = '<p>暂无用户数据</p>';
            }
        }

        // 快速填充更新表单
        function fillUpdateForm(id, username, realName, phone, role) {
            document.getElementById('updateUserId').value = id;
            document.getElementById('updateUsername').value = username;
            document.getElementById('updateRealName').value = realName;
            document.getElementById('updatePhone').value = phone;
            document.getElementById('updateRole').value = role;
            
            // 滚动到更新部分
            document.querySelector('.section:nth-child(5)').scrollIntoView({ behavior: 'smooth' });
        }

        // 快速删除
        async function quickDelete(id) {
            if (confirm(`确定要删除用户 ID: ${id} 吗？`)) {
                const result = await makeRequest(`${API_BASE}/${id}`, 'DELETE');
                displayResponse('deleteResponse', result);
                
                if (result.success) {
                    getUserList(); // 刷新列表
                }
            }
        }

        // 获取单个用户
        async function getUserById() {
            const userId = document.getElementById('getUserId').value;
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            const result = await makeRequest(`${API_BASE}/${userId}`);
            displayResponse('getUserResponse', result);
        }

        // 更新用户
        async function updateUser() {
            const userId = document.getElementById('updateUserId').value;
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            const updateData = {
                username: document.getElementById('updateUsername').value,
                password: document.getElementById('updatePassword').value,
                real_name: document.getElementById('updateRealName').value,
                phone: document.getElementById('updatePhone').value,
                role: document.getElementById('updateRole').value
            };

            // 移除空值
            Object.keys(updateData).forEach(key => {
                if (!updateData[key]) delete updateData[key];
            });

            const result = await makeRequest(`${API_BASE}/${userId}`, 'PUT', updateData);
            displayResponse('updateResponse', result);

            if (result.success) {
                getUserList(); // 刷新列表
            }
        }

        // 删除单个用户
        async function deleteUser() {
            const userId = document.getElementById('deleteUserId').value;
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            if (confirm(`确定要删除用户 ID: ${userId} 吗？`)) {
                const result = await makeRequest(`${API_BASE}/${userId}`, 'DELETE');
                displayResponse('deleteResponse', result);

                if (result.success) {
                    document.getElementById('deleteUserId').value = '';
                    getUserList(); // 刷新列表
                }
            }
        }

        // 批量删除用户
        async function batchDeleteUsers() {
            const idsInput = document.getElementById('batchDeleteIds').value;
            if (!idsInput) {
                alert('请输入要删除的用户ID列表');
                return;
            }

            const ids = idsInput.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
            if (ids.length === 0) {
                alert('请输入有效的用户ID列表');
                return;
            }

            if (confirm(`确定要删除 ${ids.length} 个用户吗？ID: ${ids.join(', ')}`)) {
                const result = await makeRequest(`${API_BASE}/batch-delete`, 'POST', { ids });
                displayResponse('deleteResponse', result);

                if (result.success) {
                    document.getElementById('batchDeleteIds').value = '';
                    getUserList(); // 刷新列表
                }
            }
        }

        // 用户登录
        async function loginUser() {
            const loginData = {
                username: document.getElementById('loginUsername').value,
                password: document.getElementById('loginPassword').value
            };

            if (!loginData.username || !loginData.password) {
                alert('请输入用户名和密码');
                return;
            }

            const result = await makeRequest(`${API_BASE}/login`, 'POST', loginData);
            displayResponse('loginResponse', result);

            if (result.success) {
                document.getElementById('loginUsername').value = '';
                document.getElementById('loginPassword').value = '';
            }
        }

        // 页面加载完成后自动获取用户列表
        window.addEventListener('load', function() {
            getUserList();
        });
    </script>
</body>
</html> 